﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Web;
using DocumentServices.Storage.FileSystem;
using System.IO;
using System.Web.Hosting;

namespace SampleBrowser.Web
{
    /// <summary>
    /// A simple document part fetch WCF service
    /// </summary>
    public class DocumentWcfService
        : IDocumentWcfService
    {
        /// <summary>
        /// Gets the specified part from given document.
        /// </summary>
        /// <param name="documentName">Name of the document.</param>
        /// <param name="partName">Name of the part.</param>
        /// <returns></returns>
        public byte[] GetDocumentPart(string documentName, string partName)
        {
            var folder = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Documents");
            var store = new FileSystemDocumentStore(folder);

            if (store.ContainsDocument(documentName)) {
                using (var document = store.OpenDocument(documentName)) {
                    var part = store.GetDocumentPart(document, partName);
                    if (part != null) {
                        using (part.Stream) {
                            var data = new byte[part.Stream.Length];
                            part.Stream.Read(data, 0, data.Length);

                            return data;
                        }
                    }
                }
            }
            else {
                // document not found
                throw new ArgumentException(string.Format("Document '{0}' not found", documentName));
            }

            // part not found
            return null;
        }
    }
}
